package com.atguigu.chap03;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
//线程间通信

class ShareDataTwo{

    Lock lock = new ReentrantLock();
    Condition conditionA = lock.newCondition();
    Condition conditionB = lock.newCondition();
    Condition conditionC = lock.newCondition();

    int flag = 1;

    //AA打印5次
    public void print5() {
        lock.lock();
        try {
            while (flag!=1){
                conditionA.await();
            }
            for (int i = 1; i <= 5; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + "---come in i="+i);
            }
            flag = 2;
            conditionB.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    //BB打印10次
    public void print10() {
        lock.lock();
        try {
            while (flag!=2){
                conditionB.await();
            }
            for (int i = 1; i <= 10; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + "---come in i="+i);
            }
            flag = 3;
            conditionC.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    //CC打印15次
    public void print15() {
        lock.lock();
        try {
            while (flag!=3){
                conditionC.await();
            }
            for (int i = 1; i <= 15; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + "---come in i="+i);
            }
            flag = 1;
            conditionA.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}

/**
 * 案例：
 *  需求：
 *          线程之间按顺序调用，实现AA->BB->CC。三个线程启动，要求如下：
 *
 *          AA打印5次，BB打印10次，CC打印15次
 *
 *          接着
 *
 *          AA打印5次，BB打印10次，CC打印15次
 *
 *          。。。打印10轮
 *  分析：
 *          1. 有一个锁Lock，3把钥匙Condition
 *          2. 有顺序通知（切换线程），需要有标识位
 *          3. 判断标志位
 *          4. 输出线程名 + 内容
 *          5. 修改标识符，通知下一个
 */
public class ThreadOrderAccess {
    public static void main(String[] args) {
        ShareDataTwo shareDataTwo = new ShareDataTwo();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                shareDataTwo.print5();
            }
        },"AA").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                shareDataTwo.print10();
            }
        },"BB").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                shareDataTwo.print15();
            }
        },"CC").start();
    }
}
